package com.xiaoyuzhou;

import com.xiaoyuzhou.logic.DataService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;

public class NetWorkReceiver extends BroadcastReceiver{
	
	/**请求最新的天气信息*/
	public static final String ACTION_REQUEST_WEATHER = "request_weather";

	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
			Bundle bundle = intent.getExtras();
			//优先处理wifi情况
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			boolean noNet = bundle.getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
			if(!noNet) {
				if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
					//wifi可用时一定会请求网络，不需要检测上次更新时间
					Intent i = new Intent(ACTION_REQUEST_WEATHER);
					i.putExtra(DataService.CHECKLASTUPDATE, false);
					context.sendBroadcast(i);
				} else if(ConnectivityManager.isNetworkTypeValid(ConnectivityManager.TYPE_MOBILE)){
					//有网络且上次刷新时间与当前时间相差12个小时时才重新请求
					context.sendBroadcast(new Intent(ACTION_REQUEST_WEATHER));
				}
			}
		}
	}

}
